import Mock from 'mockjs'

// 模拟数据库
let employeeDB = Mock.mock({
    'list|5': [{
        'id|+1': 1,
        'name': '@cname',
        'employeeId': /[A-Z]\d{5}/,
        'gender|1': [1, 2],
        'department': '技术部',
        'position': '普通员工',
        'status|1': [1, 2],
        'phone': /1[3-9]\d{9}/,
        'email': '@email'
    }]
}).list

// 获取员工列表
Mock.mock(new RegExp('/api/employees.*'), 'get', (options) => {
    const params = new URLSearchParams(options.url.split('?')[1])
    const page = parseInt(params.get('page')) || 1
    const pageSize = parseInt(params.get('pageSize')) || 1000
    const keyword = params.get('keyword')


    // 深拷贝避免污染原始数据
    let filteredList = JSON.parse(JSON.stringify(employeeDB))

    // 关键词筛选
    if (keyword) {
        filteredList = filteredList.filter(item =>
            item.name.includes(keyword) ||
            item.employeeId.includes(keyword))
    }

    const start = (page - 1) * pageSize
    const end = start + pageSize
    const pageList = filteredList.slice(start, end)

    return {
        code: 200,
        message: 'success',
        data: {
            list: pageList,
            total: filteredList.length
        }
    }
})

// 添加员工
Mock.mock('/api/employees', 'post', (options) => {
    const newEmployee = {
        id: employeeDB.length + 1,
        ...JSON.parse(options.body),
        status: 1 // 默认在职状态
    }
    employeeDB.push(newEmployee) // 添加到数组开头

    return {
        code: 200,
        message: '添加成功',
        data: newEmployee
    }
})

// 获取单个员工详情
Mock.mock(new RegExp('/api/employees/\\d+'), 'get', (options) => {
    const id = parseInt(options.url.match(/\/(\d+)$/)[1])
    const employee = employeeDB.find(item => item.id === id)

    console.log('Mock获取详情:', { id, employee }) // 调试日志
    console.log("hfsdf")

    if (!employee) {
        return { code: 404, message: '员工不存在' }
    }

    return {
        code: 200,
        data: {
            ...employee,
            status: employee.status.toString() // 确保状态是字符串
        }
    }
})

// 更新员工信息
Mock.mock(new RegExp('/api/employees/\\d+'), 'put', (options) => {
    const id = parseInt(options.url.match(/\/(\d+)$/)[1])
    const body = JSON.parse(options.body)
    const index = employeeDB.findIndex(item => item.id === id)

    console.log('Mock更新数据:', { id, body, index }) // 调试日志

    if (index === -1) {
        return { code: 404, message: '员工不存在' }
    }

    // 更新数据
    employeeDB[index] = {
        ...employeeDB[index],
        ...body,
        id: employeeDB[index].id, // 保持ID不变
        status: parseInt(body.status) // 转回数字
    }

    return {
        code: 200,
        message: '更新成功',
        data: employeeDB[index]
    }
})